/*
 * @Author: axe
 * @Email: hedgehogee@sina.com
 * @Date: 2023-04-04 10:52:53
 * @Last Modified by: axe
 * @Last Modified time: 2023-04-12 17:39:47
 */

import axios, { AxiosError } from 'axios'

const baseURL = import.meta.env.VITE_HTTP_BASE_URL
const httpCache: Map<string, AbortController> = new Map()

// 创建 axios 实例
export const http = axios.create({
  baseURL,
  timeout: 0
})

const err = (error: AxiosError): Promise<AxiosError> => {
  if (error.response) {
    if (error.response.status === 500) {
      // something todo
    }
  }
  return Promise.reject(error)
}

// request interceptor
http.interceptors.request.use(config => {
  const url = config.url as string
  const controller = new AbortController()
  const signal = controller.signal

  config.signal = signal

  if (httpCache.has(url)) {
    controller.abort()
  } else {
    httpCache.set(url, controller)
  }

  return config
}, err)

// response interceptor
http.interceptors.response.use((response) => {
  const url = response.config.url as string

  if (httpCache.has(url)) httpCache.delete(url)
  // blob file
  if (response.request.responseType === 'blob') {
    return response
  }

  return response.data
}, err)
